package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.dto.*;
import com.prd.enums.CustomerRemarkEnum;
import com.prd.mapper.CustomerFollowMapper;
import com.prd.model.CustomerFollowDO;
import com.prd.service.*;
import com.prd.tools.CopyNonNullBeanUtils;
import com.prd.util.JsonData;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户-跟进 服务实现类
 * </p>
 *
 * @author o1
 * @since 2024-01-02
 */
@Service
public class CustomerFollowServiceImpl extends ServiceImpl<CustomerFollowMapper, CustomerFollowDO> implements CustomerFollowService {

    @Autowired
    private CustomerFollowMapper followMapper;


    @Resource(name = "CustomerService")
    private CustomerService customerService;
    @Resource(name = "CustomerGuestService")
    private CustomerGuestService guestService;
    @Resource(name = "CustomerProjectService")
    private CustomerProjectService projectService;
    @Resource(name = "CustomerRemarkService")
    private CustomerRemarkService remarkService;


    @Override
    public Map<String, Object> uSearch(int page, int size, Date date, int businessManagerId, int status) {
        LambdaQueryWrapper<CustomerFollowDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerFollowDO::getBusinessManagerId, businessManagerId);
        lambdaQueryWrapper.eq(CustomerFollowDO::getStatus, status);
        lambdaQueryWrapper.eq(CustomerFollowDO::getFollowDate, date);
        Page<CustomerFollowDO> pageInfo = new Page<>(page, size);
        IPage<CustomerFollowDO> followDOIPage = followMapper.selectPage(pageInfo,lambdaQueryWrapper);
        List<CustomerFollowDTO> followDTOList = followDOIPage.getRecords().stream().map(
                this::doToDto
        ).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>(3);
        map.put("total_record", followDOIPage.getTotal());
        map.put("total_page", followDOIPage.getPages());
        map.put("current_data", followDTOList);
        return map;
    }

    @Override
    public JsonData uAdd(CustomerFollowDTO followDTO) {
        String followNo = String.valueOf(followDTO.hashCode());
        LambdaQueryWrapper<CustomerFollowDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerFollowDO::getFollowNo, followNo);
        lambdaQueryWrapper.eq(CustomerFollowDO::getBusinessManagerId, followDTO.getBusinessManagerId());
        CustomerFollowDO followDO = followMapper.selectOne(lambdaQueryWrapper);
        if (followDO == null) {
            followDO = new CustomerFollowDO();
            followDO.setFollowNo(followNo);
            CopyNonNullBeanUtils.copyProperties(followDTO, followDO);
            followMapper.insert(followDO);
            if (followDTO.getOtherBusinessManagerList() != null && followDTO.getOtherBusinessManagerList().size() > 1) {
                for (CustomerTmpEmployeeDTO employeeDTO: followDTO.getOtherBusinessManagerList()) {
                    if (employeeDTO.getBusinessManagerId() != followDTO.getBusinessManagerId()) {
                        followDTO.setBusinessManager(employeeDTO.getBusinessManager());
                        followDTO.setBusinessManagerId(employeeDTO.getBusinessManagerId());
                        followDTO.setBusinessPhone(employeeDTO.getBusinessPhone());
                        followDTO.setBusinessDepartment(employeeDTO.getBusinessDepartment());
                        followDTO.setBusinessDepartmentId(employeeDTO.getBusinessDepartmentId());
                        addOtherFollow(followNo, followDTO);
                    }
                }
            }
            if (followDTO.getGoalRemark() != null) {
                CustomerRemarkDTO goalRemarkDto = followDTO.getGoalRemark();
                goalRemarkDto.setType(CustomerRemarkEnum.FollowGoal.getCode());
                goalRemarkDto.setNo(followNo);
                remarkService.uAdd(goalRemarkDto);
            }
            return JsonData.buildSuccess(followDO);
        }
        else
            return new JsonData(-1, followDO, "已有跟进任务");
    }

    @Override
    public JsonData uDetail(String followNo, int businessManagerId, int status) {
        LambdaQueryWrapper<CustomerFollowDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerFollowDO::getFollowNo, followNo);
        lambdaQueryWrapper.eq(CustomerFollowDO::getBusinessManagerId, businessManagerId);
        if (status > 0)
            lambdaQueryWrapper.eq(CustomerFollowDO::getStatus, status);
        CustomerFollowDO followDO = followMapper.selectOne(lambdaQueryWrapper);
        if (followDO != null) {
            CustomerFollowDTO followDTO = new CustomerFollowDTO();
            CopyNonNullBeanUtils.copyProperties(followDO, followDTO);
            if (followDO.getCustomerNo() != null) {
                followDTO.setCustomerDTO(customerService.getOne(followDO.getCustomerNo()));
                if (followDO.getProjectId() != null && followDO.getProjectId().indexOf(",") != 0) {
                    List<String> projectIdList = Arrays.asList(followDO.getGuestNo().split(","));
                    List<CustomerProjectDTO> projectDTOList = projectService.searchForList(followDO.getCustomerNo());
                    List<CustomerProjectDTO> targetProjectList = new ArrayList<>();
                    projectDTOList.forEach(projectDTO -> {
                        if (projectIdList.contains(projectDTO.getProjectId()))
                            targetProjectList.add(projectDTO);
                    });
                    followDTO.setProjectDTOList(targetProjectList);
                }
            }
            if (followDO.getGuestNo() != null && followDO.getGuestNo().indexOf(",") != 0) {
                List<String> guestNoList = Arrays.asList(followDO.getGuestNo().split(","));
                List<CustomerGuestDTO> targetProjectList = new ArrayList<>();
                for (String guestNo: guestNoList) {
                    targetProjectList.add(guestService.getOneByGuestNo(guestNo));
                }
                followDTO.setGuestDTOList(targetProjectList);
            }

            LambdaQueryWrapper<CustomerFollowDO> otherWrapper = new LambdaQueryWrapper<>();
            otherWrapper.eq(CustomerFollowDO::getFollowNo, followNo);
            if (followMapper.selectCount(otherWrapper) > 1) {
                List<CustomerFollowDO> otherFollowDOList = followMapper.selectList(otherWrapper);
                for (CustomerFollowDO otherFollowDO: otherFollowDOList) {
                    if (otherFollowDO.getBusinessManagerId() != businessManagerId) {
                        CustomerTmpEmployeeDTO tmpEmployeeDTO = new CustomerTmpEmployeeDTO();
                        CopyNonNullBeanUtils.copyProperties(otherFollowDO, tmpEmployeeDTO);
                        followDTO.getOtherBusinessManagerList().add(tmpEmployeeDTO);
                    }
                }
            }
            return JsonData.buildSuccess(followDTO);
        }
        else
            return JsonData.buildError("未找到对应跟进记录");
    }

    @Override
    public JsonData uAddBusinessManager(String followNo, int businessManagerId, String businessManager, int businessDepartmentId, String businessDepartment, String businessPhone) {
        LambdaQueryWrapper<CustomerFollowDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerFollowDO::getFollowNo, followNo);
        lambdaQueryWrapper.eq(CustomerFollowDO::getBusinessManagerId, businessManagerId);
        CustomerFollowDO followDO = followMapper.selectOne(lambdaQueryWrapper);
        if (followDO == null) {
            followDO = new CustomerFollowDO();
            followDO.setFollowNo(followNo);
            LambdaQueryWrapper<CustomerFollowDO> otherWrapper = new LambdaQueryWrapper<>();
            otherWrapper.eq(CustomerFollowDO::getFollowNo, followNo);
            if (followMapper.selectCount(otherWrapper) > 1) {
                List<CustomerFollowDO> otherFollowDOList = followMapper.selectList(otherWrapper);
                CustomerFollowDO otherFollowDO = otherFollowDOList.get(0);
                CopyNonNullBeanUtils.copyProperties(otherFollowDO, followDO);
                followDO.setBusinessManager(businessManager);
                followDO.setBusinessManagerId(businessManagerId);
                followDO.setBusinessDepartment(businessDepartment);
                followDO.setBusinessDepartmentId(businessDepartmentId);
                followDO.setBusinessPhone(businessPhone);
                followMapper.insert(followDO);
            }
            return JsonData.buildSuccess(followDO);
        }
        else
            return JsonData.buildError("没有找到对应的跟进任务");
    }

    @Override
    public JsonData uUpdate(CustomerFollowDTO followDTO) {
        LambdaQueryWrapper<CustomerFollowDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerFollowDO::getFollowNo, followDTO.getFollowNo());
        lambdaQueryWrapper.eq(CustomerFollowDO::getBusinessManagerId, followDTO.getBusinessManagerId());
        CustomerFollowDO followDO = followMapper.selectOne(lambdaQueryWrapper);
        if (followDO == null) {
            return JsonData.buildError("未找到对应跟进任务");
        }else {
            CopyNonNullBeanUtils.copyProperties(followDTO, followDO);
            followMapper.update(followDO, lambdaQueryWrapper);
            if (followDTO.getResultRemark() != null) {
                CustomerRemarkDTO resultRemarkDto = followDTO.getResultRemark();
                resultRemarkDto.setType(CustomerRemarkEnum.FollowResultReport.getCode());
                resultRemarkDto.setNo(followDO.getFollowNo());
                remarkService.uAdd(resultRemarkDto);
            }
            if (followDTO.getReplenishRemarkList() != null && followDTO.getReplenishRemarkList().size() > 0) {
                for (CustomerRemarkDTO replenishRemarkDto: followDTO.getReplenishRemarkList()) {
                    replenishRemarkDto.setType(CustomerRemarkEnum.FollowReplenish.getCode());
                    replenishRemarkDto.setNo(followDTO.getFollowNo());
                    remarkService.uUpdateAndAdd(replenishRemarkDto);
                }
            }
            return JsonData.buildSuccess(followDO);
        }
    }

    @Override
    public JsonData uFinish(CustomerFollowDTO followDTO) {
        followDTO.setStatus(4);
        followDTO.setFollowFinishDate(new Date());
        return uUpdate(followDTO);
    }

    @Override
    public JsonData uArrival(CustomerFollowDTO followDTO) {
        followDTO.setStatus(2);
        followDTO.setFollowActualDate(new Date());
        return uUpdate(followDTO);
    }

    private void addOtherFollow(String followNo, CustomerFollowDTO followDTO) {
        LambdaQueryWrapper<CustomerFollowDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CustomerFollowDO::getFollowNo, followNo);
        lambdaQueryWrapper.eq(CustomerFollowDO::getBusinessManagerId, followDTO.getBusinessManagerId());
        CustomerFollowDO followDO = followMapper.selectOne(lambdaQueryWrapper);
        if (followDO == null) {
            followDO = new CustomerFollowDO();
            followDO.setFollowNo(followNo);
            CopyNonNullBeanUtils.copyProperties(followDTO, followDO);
            followMapper.insert(followDO);
        }
    }


    private CustomerFollowDTO doToDto(CustomerFollowDO followDO) {
        CustomerFollowDTO followDTO = new CustomerFollowDTO();
        BeanUtils.copyProperties(followDO, followDTO);
        return followDTO;
    }
}
